﻿using System;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;

namespace Core.Utility
{
    public static class SerializerXml<T> where T : new()
    {
        private static readonly object lockObject = new object();
        public static T Read(string filePath)
        {
            try
            {
                if (File.Exists(filePath))
                {
                    return ReadObject(filePath);
                }
                else
                {
                    WriteObject(new T(), filePath);//文件不存在默认创建一份
                    return ReadObject(filePath);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message,ex);
            }                
        }

        static T ReadObject(string filePath)
        {
            lock (lockObject)
            {
                try
                {
                    using (FileStream fs = new FileStream(filePath, FileMode.Open))
                    {
                        XmlDictionaryReader reader = XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());

                        DataContractSerializer ser = new DataContractSerializer(typeof(T));

                        T obj = (T)ser.ReadObject(reader, true);

                        reader.Close();
                        return obj;
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message, ex);
                }
            }
        }

        public static void WriteObject(T obj , string filePath)
        {
            lock (lockObject)
            {
                try
                {
                    using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
                    {
                        //新建序列化对象
                        DataContractSerializer dataContractSerializer = new DataContractSerializer(typeof(T));
                        //进行序列化
                        dataContractSerializer.WriteObject(fileStream, obj);
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception(ex.Message, ex);
                }
            }
        }
      
    }
}
